package controller

import (
	"miao/service"
	"miao/util"
	"net/http"
	"path/filepath"
	"strconv"

	"github.com/gin-gonic/gin"
)

// OSSUploadHandler OSSUploadHandler处理文件上传到OSS
func OSSUploadHandler(c *gin.Context) {
	// Example: retrieve file from form
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, util.Fail(500, "Failed to save file"))
		return
	}

	fileName := "D:/Code/Go/miao_dome/util/oss/" + file.Filename
	if err2 := c.SaveUploadedFile(file, fileName); err2 != nil {
		c.JSON(http.StatusInternalServerError, util.Fail(500, "Failed to save file"))
		return
	}
	path := "http://localhost:8080/oss/"
	service.SaveFile(path, file.Filename)
	c.JSON(http.StatusOK, util.Success(path+"download/"+fileName))
}

// OssDownloadHandler OSSDownloadHandler处理从OSS下载文件。
func OssDownloadHandler(c *gin.Context) {
	fileName := c.Param("file")
	c.Header("Content-Type", "application/octet-stream")
	// Example: retrieve file from form
	filepath := filepath.Join("D:/Code/Go/miao_dome/util/oss/", fileName)
	c.File(filepath)
}

// OssPreviewHandler 文件预览
func OssPreviewHandler(c *gin.Context) {

	fileName := c.Param("file")

	c.Header("Content-Type", "image/jpg;charset=UTF-8")

	join := filepath.Join("D:/Code/Go/miao_dome/util/oss/", fileName)

	fileType := util.GetTypeByMagic(join)

	switch fileType {
	case "image/jpeg":
		c.Header("Content-Type", "image/jpeg;charset=UTF-8")
	case "image/png":
		c.Header("Content-Type", "image/png;charset=UTF-8")
	case "application/pdf":
		c.Header("Content-Type", "application/pdf;charset=UTF-8")
	case "video/mp4":
		c.Header("Content-Type", "video/mp4;charset=UTF-8")
	default:
		c.Header("Content-Type", "application/octet-stream")
	}

	c.File(join)
}

func PageByOss(c *gin.Context) {
	currentPage := c.DefaultQuery("currentPage", "1")
	pageSize := c.DefaultQuery("pageSize", "10")
	username := c.Query("username")
	intCurrentPage, _ := strconv.Atoi(currentPage)
	intPageSize, _ := strconv.Atoi(pageSize)
	result := service.PageFile(intCurrentPage, intPageSize, username)
	c.JSON(http.StatusOK, result)
}

func DropFile(c *gin.Context) {
	id := c.Param("id")
	result := service.DropFile(id)
	c.JSON(http.StatusOK, result)
}
